package com.hiwan.system.service.auth;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hiwan.system.cache.SysCacheService;
import com.hiwan.system.dao.auth.AuthInfoDao;
import com.hiwan.system.dao.sequence.SeqDao;
import com.hiwan.system.pojo.AuthInfo;
import com.hiwan.system.pojo.RoleInfo;
import com.hiwan.system.pojo.UserInfo;
import com.hiwan.system.pojo.UserRelation;
import com.hiwan.system.service.role.RoleService;
import com.hiwan.system.service.user.UserService;

/**
 * 转授权业务处理类
 * Datetime   ： 2013-12-30 上午9:36:12<br>
 * Title      :  AuthInfoService.java<br>
 * Copyright  :  Copyright (c) 2013<br>
 * Company    :  HIWAN<br>
 * @author llg
 *
 */
@Component
@Service
@Transactional
public class AuthInfoService {
	
	@Autowired
	private AuthInfoDao authInfoDao;
	
	@Autowired
	private SeqDao seqDao;
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserService userService;
	@Autowired
	private SysCacheService sysCacheService;
	
	/**
	 * 查询转授权信息列表(分页)
	 * @param authInfo
	 * @return
	 */
	public List<AuthInfo> selectAuthInfoListPage(AuthInfo authInfo) {
		return authInfoDao.selectAuthInfoListPage(authInfo);
	}

	/**
	 * 查询转授权信息列表(不分页)
	 * @param authInfo
	 * @return
	 */
	public List<AuthInfo> selectAuthInfoList(AuthInfo authInfo) {
		return authInfoDao.selectAuthInfoList(authInfo);
	}

	/**
	 * 查询转授权信息
	 * @param authUser
	 * @param seqNo
	 * @return
	 */
	public AuthInfo selectAuthInfoById(String authUser,int seqNo) {
		return authInfoDao.selectAuthInfoById(authUser,seqNo);
	}
	
	/**
	 *判断授权信息是否存在
	 * 
	 * @param AuthInfo
	 * @return
	 */
	public int isExistAuthInfo(AuthInfo info) {
		return authInfoDao.isExistAuthInfo(info);
	}

	/**
	 * 插入转授权信息
	 * @param authInfo
	 * @return
	 */
	public int insertAuthInfo(AuthInfo authInfo,String isAdministrator) {
		Integer seqNo = this.selectMaxSeqNoByUser(authInfo.getAuthUser());
		authInfo.setSeqNo(seqNo);
		this.sendMessageInfo(authInfo, isAdministrator);
		return authInfoDao.insertAuthInfo(authInfo);
	}

	/**
	 * 更新转授权信息
	 * @param authInfo
	 * @return
	 */
	public int updateAuthInfo(AuthInfo authInfo,String isAdministrator) {
		AuthInfo po = this.selectAuthInfoById(authInfo.getAuthUser(),authInfo.getSeqNo());
		if(!authInfo.getAuthedUser().equals(po.getAuthedUser())||!authInfo.getAuthEndTime().equals(po.getAuthEndTime())){
			this.sendMessageInfo(authInfo, isAdministrator);
		}
		
		return authInfoDao.updateAuthInfo(authInfo);
	}
	
	/**
	 * 发送短信
	 * @param authInfo
	 * @param isAdministrator
	 */
	public void sendMessageInfo(AuthInfo authInfo,String isAdministrator){
		if("1".equals(isAdministrator)){
			//调用短信发送接口
			boolean isPresident = false;//flowPartUtilService.isPresident(authInfo.getAuthUser());
			if(!isPresident){
				//省市分行行长，副行长不发短信
				this.sendMessage(authInfo);
			}
		}
	}
	
	/**
	 * 短信回复，更新授权状态
	 * @param content
	 */
	public void updateAuthInfoStatus(String content){
		if (content != null) {
			String randomStr = null;
			if(content.length()==10){
				randomStr = content.substring(4);
				AuthInfo info = new AuthInfo();
				info.setVerifyCode(randomStr);
				List<AuthInfo> infoList = this.selectAuthInfoList(info);
				if(infoList!=null&&infoList.size()>0){
					AuthInfo po = infoList.get(0);
					po.setAuthStatus("1");//设置转授权状态为有效
					this.updateAuthInfo(po, "0");
				}
			}
		}
	}
	
	/**
	 * 调用短信发送接口
	 * @param authInfo
	 * @return
	 */
	public boolean sendMessage(AuthInfo authInfo){
		/*SysParameterInfo paraInfo = sysCacheService.getSysParameter("sms_flag",
				"*", "*");*/
		//String content = "您有一笔转授权记录待确认，被授权人["+userService.getUserName(authInfo.getAuthedUser())+"]," +
		//		"授权到期时间"+authInfo.getAuthEndTime()+",如果确认授权，请回复："+paraInfo.getParam1()+""+authInfo.getVerifyCode()+"";
		//boolean isSuccess = smsSendService.send(authInfo.getAuthUser(), content, "转授权");
		return true;
	}
	
	/**
	 * 系统管理员授权时的相关校验
	 * @param authInfo
	 * @param flag 1-新增，2-修改
	 * @return
	 */
	public String[] checkAuthInfo(AuthInfo authInfo,String flag,String isAdministrator){
		String[] ret = null;
		int num = this.isExistAuthInfo(authInfo);
    	boolean telphone = this.isExistTelphone(authInfo.getAuthUser());
    	if(num>0&&"1".equals(flag)){
    		ret = new String[]{"fail","该授权时间区间内已经存在授权记录！"};
    	}else if(!telphone&&"1".equals(isAdministrator)){
    		ret = new String[]{"fail","授权用户的手机号未填写完整，无法发送短信通知进行授权确认！"};
    	}else{
    		ret = new String[]{"ok",""};
    	}	
    	return ret;
	}
	
	/**
	 * 判断用户手机编号是否保存完整
	 * @param userId
	 * @return
	 */
	public boolean isExistTelphone(String userId){
		UserInfo recvUser = userService.getUserInfo(userId);
		if (StringUtils.isEmpty(recvUser.getMobileNo())) {
			return false;
		}
		return true;
	}

	/**
	 * 删除转授权信息
	 * @param queueNo
	 * @param orgId
	 * @return
	 */
	public int deleteAuthInfo(String authUser,int seqNo) {
		return authInfoDao.deleteAuthInfoById(authUser,seqNo);
	}
	
	/**
	 * 查询当前授权用户最大序列号
	 * @param authUser
	 * @return
	 */
	public Integer selectMaxSeqNoByUser(String authUser){
		Integer maxSeqNo = authInfoDao.selectMaxSeqNoByUser(authUser);
		if(maxSeqNo==null||"".equals(maxSeqNo)){
			maxSeqNo = 1;
		}else{
			maxSeqNo = maxSeqNo + 1;
		}
		return maxSeqNo;
	}
	
	/**
	 * 查询角色列表
	 * @param userId
	 * @return
	 */
	public List<RoleInfo> selectRoleListById(String userId){
		List<RoleInfo> roleList = new ArrayList<RoleInfo>();
		List<UserRelation> ur = userService.getUserRelations(userId);
		if(ur!=null&&ur.size()>0){
			UserRelation urPO = ur.get(0);
			List<String> roleStr = urPO.getRoleIds();
			if(roleStr!=null&&roleStr.size()>0){
				for(String roleId : roleStr){
					RoleInfo newPO = roleService.get(roleId);
					roleList.add(newPO);
				}
			}
		}
		
		return roleList;
	}
	
	/**
	 * 查询选择中的角色
	 * @param authInfo
	 * @return
	 */
	public List<RoleInfo> setChoosedRoleId(AuthInfo authInfo){
		List<RoleInfo> list = new ArrayList<RoleInfo>();
		String[] roleId = authInfo.getAuthedRole().split(",");
		if(roleId!=null&&roleId.length>0){
			for(int i=0;i<roleId.length;i++){
				RoleInfo newPO = new RoleInfo();
				newPO.setRoleId(roleId[i].trim());
				list.add(newPO);
			}
		}
		return list;
	}
	
	/**
	 * 设置所选用户的角色信息
	 * @param roleIdStr
	 * @return
	 */
	public Object[] setRoleName(String roleIdStr){
		Object[] ret = null;
		if(roleIdStr!=null){
			String[] roleArr = roleIdStr.split(",");
			if(roleArr!=null&&roleArr.length>0){
				ret = new Object[roleArr.length+2];
				ret[0] = "ok";
				ret[1] = String.valueOf(roleArr.length);
				for(int i=0;i<roleArr.length;i++){
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("roleId",roleArr[i]);
					map.put("roleName", roleService.get(roleArr[i]).getRoleName());
					ret[i+2] = map;
				}
			}
		}else{
			ret = new String[]{"ok",""};
		}
		return ret;
	}
	
	
	/**
	 * 获取不重复的随机数
	 * @return
	 */
	public String getRandomNoRepeat(){
		while(true){
			String randomStr = this.getRandomNum(6);
			AuthInfo info = new AuthInfo();
			info.setVerifyCode(randomStr);
			List<AuthInfo> authInfoList = this.selectAuthInfoList(info);
			if(authInfoList==null||authInfoList.size()<=0){
				return randomStr;
			}
		}
	}
	
	/**
	 * 获取随机数
	 * @param num 随机数位数
	 * @return
	 */
	public String getRandomNum(int num){
		Random random = new Random();
		String s="";
		for (int i=0;i<num;i++){
		    String rand=String.valueOf(random.nextInt(10));
		       s+=rand;
		} 
		return s;
	}


	public AuthInfoDao getAuthInfoDao() {
		return authInfoDao;
	}

	public void setAuthInfoDao(AuthInfoDao authInfoDao) {
		this.authInfoDao = authInfoDao;
	}

	public SeqDao getSeqDao() {
		return seqDao;
	}

	public void setSeqDao(SeqDao seqDao) {
		this.seqDao = seqDao;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public SysCacheService getSysCacheService() {
		return sysCacheService;
	}

	public void setSysCacheService(SysCacheService sysCacheService) {
		this.sysCacheService = sysCacheService;
	}
}
